﻿/**
 * ...
 * @author Innokentiy Shuvalov
 */

package list;

import flash.display.Bitmap;
import flash.display.BitmapData;
import haxe.Timer;
import flash.net.URLRequest;
import flash.Lib;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;

class ImageLoader extends Bitmap {
	private var timer 			: Timer;
	public  var imageAdress 	: String;
	private var pictureWidth 	: Int;
	private var pictureHeight   : Int;
	private var loader 			: Loader;
	
public function new ( adress : String, pictureWidth : Int, pictureHeight : Int) {
		
		super();
		this.pictureWidth = pictureWidth;
		this.pictureHeight = pictureHeight;
		imageAdress = adress;
		load();
	}
	
	public function load() {
        timer = new Timer( 1 );
        timer.run = isReady;
    }
    
    private function isReady() {
        if( Lib.current.stage != null ) {
            if( Std.is( Lib.current.stage.stageWidth , Int ) ) {
				var loader : Loader = new Loader();
				//loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, function( e: IOErrorEvent = null ):Void {  trace( 'oops not found ' + _img );});
				loader.contentLoaderInfo.addEventListener( Event.INIT, loaded ); 
				loader.load( new URLRequest( imageAdress ) );
				
                timer.stop();
            }
        }
    }
    
    private function loaded( e: Event ) { 
        e.target.content.smoothing = true;
        this.bitmapData = cast( e.target.content, Bitmap ).bitmapData ;
		processScale();
    }
	
	private function processScale() {
		var ph:Int = this.pictureHeight;
		var pw:Int = this.pictureWidth ;
        var h:Int = this.bitmapData.height;
		var w:Int = this.bitmapData.width;
		
		this.scaleY = (ph > h) ?  1.0  : (ph / h);
        this.scaleX = (pw > w) ?  1.0  :  (pw / w);
	
		
	}
}